package main

import (
	"fmt"
	"sync/atomic"
	"time"
)

func tryDefer() {
	defer fmt.Println(1)
	defer fmt.Println(2)
	fmt.Println(3)
	panic("error")
}

// 统计耗时
func handler(a, b int) string {
	t0 := time.Now()
	defer func() {
		fmt.Printf("1.use time %d ms \n", time.Since(t0).Microseconds())
	}()
	if a > b {
		time.Sleep(10 * time.Microsecond)
		return "ok"
	} else {
		time.Sleep(200 * time.Microsecond)
		return "ok"
	}
}

var (
	concurrent       int32
	concurrent_limit = make(chan struct{}, 10)
)

// 限流
func readDb() string {
	atomic.AddInt32(&concurrent, 1)
	fmt.Printf("readDb()调用并发度 %d\n", atomic.LoadInt32(&concurrent))
	time.Sleep(200 * time.Millisecond)
	atomic.AddInt32(&concurrent, -1)
	return "ok"
}
func handler2() {
	concurrent_limit <- struct{}{}
	readDb()
	<-concurrent_limit
	return
}

func main() {
	//tryDefer()
	//handler(3, 4)
	for i := 0; i < 100; i++ {
		go handler2()
	}
	time.Sleep(3 * time.Second)
}
